package a.a.a;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings;

import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.bytedance.novel.pangolin.NovelConfig;
import com.bytedance.novel.pangolin.NovelSDK;
import com.bytedance.novel.pangolin.PangolinDocker;
import com.bytedance.novel.pangolin.data.INovelInitListener;
import com.bytedance.novel.pangolin.data.NormalFontType;
import com.bytedance.novel.pangolin.data.ReaderFontType;
import com.bytedance.sdk.dp.DPSdk;
import com.bytedance.sdk.dp.DPSdkConfig;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.stub.activity.Stub_Activity;
import com.bytedance.sdk.openadsdk.stub.activity.Stub_SingleTask_Activity;
import com.bytedance.sdk.openadsdk.stub.activity.Stub_SingleTask_Activity_T;
import com.bytedance.sdk.openadsdk.stub.activity.Stub_Standard_Activity;
import com.bytedance.sdk.openadsdk.stub.activity.Stub_Standard_Activity_T;
import com.bytedance.sdk.openadsdk.stub.activity.Stub_Standard_Landscape_Activity;
import com.bytedance.sdk.openadsdk.stub.activity.Stub_Standard_Portrait_Activity;
import com.kwad.sdk.api.KsAdSDK;
import com.kwad.sdk.api.SdkConfig;
import com.ss.android.downloadlib.activity.JumpKllkActivity;
import com.ss.android.downloadlib.activity.TTDelegateActivity;
import com.ss.android.downloadlib.addownload.compliance.AppDetailInfoActivity;
import com.ss.android.downloadlib.addownload.compliance.AppPrivacyPolicyActivity;
import com.ss.android.socialbase.appdownloader.view.DownloadTaskDeleteActivity;
import com.ss.android.socialbase.appdownloader.view.JumpUnknownSourceActivity;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.yuzhitong.shapi.BuildConfig;
import com.yuzhitong.shapi.R;
import com.yuzhitong.shapi.activity.PlayActivity;
import com.yuzhitong.shapi.activity.PlayNewActivity;
import com.yuzhitong.shapi.base.Contents;
import com.yuzhitong.shapi.bean.PlayAddressBean;
import com.yuzhitong.shapi.bean.PlayHistoryBean;
import com.yuzhitong.shapi.util.ACache;
import com.yuzhitong.shapi.util.LoggerUtil;
import com.yuzhitong.shapi.util.TTAdManagerHolder;

import java.util.List;
import java.util.UUID;

import me.jessyan.autosize.AutoSizeConfig;

//import org.adblockplus.libadblockplus.android.AdblockEngine;
//import org.adblockplus.libadblockplus.android.SingleInstanceEngineProvider;

/**
 * 自定义Application
 * <p>
 * 可进行应用初始化操作
 */
public class MyApplication extends MultiDexApplication {

    private static final String PREFS_SETTING = "PREFS_SETTING";

    private static Application thisApplication;
    private static boolean isProxy = false;

    public static ACache aCache;
    private static SharedPreferences sp;
    public static String androidId;

    public static PlayAddressBean playAddressBean;


    private List<PlayHistoryBean> playHistories;

    public static boolean isIsProxy() {
        return isProxy;
    }

    public static void setIsProxy(boolean isProxy) {
        MyApplication.isProxy = isProxy;
    }

    //    private final SingleInstanceEngineProvider.EngineCreatedListener engineCreatedListener =
    //            new SingleInstanceEngineProvider.EngineCreatedListener() {
    //                @Override
    //                public void onAdblockEngineCreated(AdblockEngine engine) {
    //                    // 设置规则地址
    //                    //                    engine.setSubscription("");
    //
    //                }
    //            };

    @Override
    public void onCreate() {
        super.onCreate();
        thisApplication = this;
        MultiDex.install(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                aCache = ACache.get(MyApplication.this);

                clearTTActivity();

                if (isAgree()) {

                    sp = getSharedPreferences(PREFS_SETTING, MODE_PRIVATE);
                    androidId = Settings.System.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

                    if (androidId == null) {
                        if (aCache.getAsString("deviceIdService") != null) {
                            androidId = aCache.getAsString("deviceIdService");
                        }else{
                            androidId = "random" + UUID.randomUUID().toString();
                            aCache.put("deviceIdService", androidId);
                        }
                    }

                    //友盟正式初始化
                    UMConfigure.preInit(MyApplication.this, Contents.YM_SDK_ID, BuildConfig.CHANNEL_NAME);
                    UMConfigure.init(MyApplication.this, Contents.YM_SDK_ID, BuildConfig.CHANNEL_NAME, UMConfigure.DEVICE_TYPE_PHONE, "");
                    TTAdManagerHolder.get().init(MyApplication.this, new TTAdSdk.InitCallback() {
                        @Override
                        public void success() {
                            LoggerUtil.i("穿山甲SDK初始化成功");
                        }

                        @Override
                        public void fail(int i, String s) {
                            LoggerUtil.i("穿山甲SDK初始化失败");
                        }
                    });
                    initUmShear();
                    initDpSdk();
                    initBookDpSdk();
                    initKSSDK(thisApplication);
                }

            }
        }).start();
    }

    private static void clearTTActivity() {
        AutoSizeConfig.getInstance().getExternalAdaptManager()
                .addCancelAdaptOfActivity(PlayActivity.class)
                .addCancelAdaptOfActivity(PlayNewActivity.class)
                .addCancelAdaptOfActivity(Stub_Activity.class)
                .addCancelAdaptOfActivity(Stub_SingleTask_Activity.class)
                .addCancelAdaptOfActivity(Stub_SingleTask_Activity_T.class)
                .addCancelAdaptOfActivity(Stub_Standard_Activity.class)
                .addCancelAdaptOfActivity(Stub_Standard_Activity_T.class)
                .addCancelAdaptOfActivity(Stub_Standard_Landscape_Activity.class)
                .addCancelAdaptOfActivity(Stub_Standard_Portrait_Activity.class)
                .addCancelAdaptOfActivity(AppPrivacyPolicyActivity.class)
                .addCancelAdaptOfActivity(AppDetailInfoActivity.class)
                .addCancelAdaptOfActivity(TTDelegateActivity.class)
                .addCancelAdaptOfActivity(JumpKllkActivity.class)
                .addCancelAdaptOfActivity(DownloadTaskDeleteActivity.class)
                .addCancelAdaptOfActivity(JumpUnknownSourceActivity.class);
    }


    public static void initKSSDK(Context appContext) {
        KsAdSDK.init(appContext, new SdkConfig.Builder()
                .appId(Contents.KS_SDK_APP_ID) // 测试aapId，请联系快⼿平台申请正式AppId，必填
                .appName(thisApplication.getString(R.string.app_name)) // 测试appName，请填写您应⽤的名称，⾮必填
                .showNotification(true) // 是否展示下载通知栏
                .debug(BuildConfig.DEBUG) // 是否开启sdk 调试⽇志 可选
                .build());
    }


    /**
     * 获取首页导航点击广告间隔时间
     */
    private static final long TIME_DEFAULT = 120;

    public static long getHomeClickTimeout() {
        if (aCache == null) {
            return TIME_DEFAULT * 1000;
        }
        String timeoutStr = aCache.getAsString(Contents.CACHE_KEY_HOME_CLICK_TIMEOUT);
        try {
            long timeout = Long.parseLong(timeoutStr);
            if (timeout > 0) {
                return timeout * 60 * 1000;
            } else {
                return timeout;
            }
        } catch (NumberFormatException ignored) {
        }
        return TIME_DEFAULT * 1000;
    }

    private void initUmShear(){
        // 微信设置
        PlatformConfig.setWeixin("wxdc1e388c3822c80b","3baf1193c85774b3fd9d18447d76cab0");
        PlatformConfig.setWXFileProvider(BuildConfig.APPLICATION_ID + ".fileprovider");
        // QQ设置
        PlatformConfig.setQQZone("101830139","5d63ae8858f1caab67715ccd6c18d7a5");
        PlatformConfig.setQQFileProvider(BuildConfig.APPLICATION_ID + ".fileprovider");
        // 新浪微博设置
        PlatformConfig.setSinaWeibo("3921700954","04b48b094faeb16683c32669824ebdad","http://sns.whalecloud.com");
        PlatformConfig.setSinaFileProvider(BuildConfig.APPLICATION_ID + ".fileprovider");
        // 钉钉设置
        PlatformConfig.setDing("dingoalmlnohc0wggfedpk");
        PlatformConfig.setDingFileProvider(BuildConfig.APPLICATION_ID + ".fileprovider");
        // 企业微信设置
        PlatformConfig.setWXWork("wwac6ffb259ff6f66a","EU1LRsWC5uWn6KUuYOiWUpkoH45eOA0yH-ngL8579zs","1000002","wwauthac6ffb259ff6f66a000002");
        PlatformConfig.setWXWorkFileProvider(BuildConfig.APPLICATION_ID + ".fileprovider");
        PlatformConfig.setAlipay("2015111700822536");
    }


    /**
     * 初始化穿山甲内容输出
     */
    public static void initDpSdk() {
        TTAdManagerHolder.get().init(thisApplication, new TTAdSdk.InitCallback() {
            @Override
            public void success() {
                LoggerUtil.d("穿山甲SDK初始化成功");

                DPSdkConfig.Builder builder = new DPSdkConfig.Builder()
                        .debug(true)
                        .needInitAppLog(false)
                        .initListener(new DPSdkConfig.InitListener() {
                            @Override
                            public void onInitComplete(boolean b, String s) {
                                LoggerUtil.e("初始化穿山甲内容输出= " + b + "  msg:" + s);
                            }
                        });
                DPSdk.init(thisApplication, "SDK_Setting_5329568.json", builder.build());

                // 初始化穿山甲聚合广告SDK
                initBookDpSdk();
                initKSSDK(thisApplication);
                clearTTActivity();
            }

            @Override
            public void fail(int i, String s) {
                LoggerUtil.i("穿山甲SDK初始化失败");
            }
        });
    }

    /**
     * 初始化穿山甲内容输出
     */
    public static void initBookDpSdk() {
        NovelConfig config = new NovelConfig.Builder()
                .appName(thisApplication.getString(R.string.app_name_english)) //接入小说SDK的App的英文名 必填
                .appVersionName(BuildConfig.VERSION_NAME) //接入小说SDKApp的版本名称 必填
                .appVersionCode(BuildConfig.VERSION_CODE) //接入小说SDK App的版本号 必填
                .channel("all") //渠道号维度。开发者自定义字符串即可(建议不要包含test)。选填
                .initInnerApplog(true) // 是否使用小说sdk来初始化applog sdk。默认为false，需要开发者在App中单独初始化applog sdk，且必须在小说sdk之前初始化。
                .initInnerOpenAdSdk(false) //是否使用小说sdk来初始化广告sdk，如果为true，需要设置siteId。默认为false，需开发者在App中单独初始化广告sdk并在小说sdk之前初始化。
                .jsonFileName("SDK_Setting_5329568.json")//json配置文件的名称 必填
                .normalFontSize(NormalFontType.NORMAL) //全局字号大小 可选
                .readerFontSize(ReaderFontType.TWO) //阅读器字号大小 可选
                // 初始化成功的回调,如果初始化失败可以通过控制台，log，小说里面所有的接口调用都需要在初始化成功
                .initListener(new INovelInitListener() {
                    @Override
                    public void onInitComplete(boolean b) {

                    }
                })
                .build();


        NovelSDK.INSTANCE.attach(new PangolinDocker(config), thisApplication);
    }

//    /**
//     * 初始化穿山甲内容输出
//     */
//    public static void initDpSdk() {
//        NovelConfig config = new NovelConfig.Builder()
//                .appName(thisApplication.getString(R.string.app_name_english)) //接入小说SDK的App的英文名 必填
//                .appVersionName(BuildConfig.VERSION_NAME) //接入小说SDKApp的版本名称 必填
//                .appVersionCode(BuildConfig.VERSION_CODE) //接入小说SDK App的版本号 必填
//                .channel("all") //渠道号维度。开发者自定义字符串即可(建议不要包含test)。选填
//                .initInnerApplog(true) // 是否使用小说sdk来初始化applog sdk。默认为false，需要开发者在App中单独初始化applog sdk，且必须在小说sdk之前初始化。
//                .initInnerOpenAdSdk(false) //是否使用小说sdk来初始化广告sdk，如果为true，需要设置siteId。默认为false，需开发者在App中单独初始化广告sdk并在小说sdk之前初始化。
//                .jsonFileName("SDK_Setting_5329568.json")//json配置文件的名称 必填
//                .normalFontSize(NormalFontType.NORMAL) //全局字号大小 可选
//                .readerFontSize(ReaderFontType.TWO) //阅读器字号大小 可选
//                // 初始化成功的回调,如果初始化失败可以通过控制台，log，小说里面所有的接口调用都需要在初始化成功
//                .initListener(new INovelInitListener() {
//                    @Override
//                    public void onInitComplete(boolean b) {
//
//                    }
//                })
//                .build();
//
//
//        NovelSDK.INSTANCE.attach(new PangolinDocker(config), thisApplication);
//
//
//
////        DPSdkConfig.Builder builder = new DPSdkConfig.Builder()
////                .debug(true)
////                .needInitAppLog(false)
////                .initListener(new DPSdkConfig.InitListener() {
////                    @Override
////                    public void onInitComplete(boolean b, String s) {
////                        LoggerUtil.e("初始化穿山甲内容输出= " + b);
////                    }
////                });
//////                .initListener(new DPSdkConfig.InitListener() {
//////                    @Override
//////                    public void onInitComplete(boolean b) {
//////                        LoggerUtil.e("初始化穿山甲内容输出= " + b);
//////
//////                    }
//////                });
////        DPSdk.init(thisApplication, "SDK_Setting_5329568.json", builder.build());
//    }
//
//    /**
//     * 初始化穿山甲内容输出
//     */
//    public static void initBookDpSdk() {
//        NovelConfig config = new NovelConfig.Builder()
//                .appName(thisApplication.getString(R.string.app_name_english)) //接入小说SDK的App的英文名 必填
//                .appVersionName(BuildConfig.VERSION_NAME) //接入小说SDKApp的版本名称 必填
//                .appVersionCode(BuildConfig.VERSION_CODE) //接入小说SDK App的版本号 必填
//                .channel(BuildConfig.FLAVOR) //渠道号维度。开发者自定义字符串即可(建议不要包含test)。选填
//                .initInnerApplog(true) // 是否使用小说sdk来初始化applog sdk。默认为false，需要开发者在App中单独初始化applog sdk，且必须在小说sdk之前初始化。
//                .initInnerOpenAdSdk(false) //是否使用小说sdk来初始化广告sdk，如果为true，需要设置siteId。默认为false，需开发者在App中单独初始化广告sdk并在小说sdk之前初始化。
//                .jsonFileName("SDK_Setting_5329568.json")//json配置文件的名称 必填
//                .normalFontSize(NormalFontType.NORMAL) //全局字号大小 可选
//                .readerFontSize(ReaderFontType.TWO) //阅读器字号大小 可选
//                // 初始化成功的回调,如果初始化失败可以通过控制台，log，小说里面所有的接口调用都需要在初始化成功
//                .initListener(new INovelInitListener() {
//                    @Override
//                    public void onInitComplete(boolean b) {
//
//                    }
//                })
//                .build();
//
//
//        NovelSDK.INSTANCE.attach(new PangolinDocker(config), thisApplication);
//    }


    /**
     * 判断是否打开广告
     * 默认未打开
     *
     * @return 广告是否打开
     */
    public static boolean isOpenAd() {
        if (aCache == null) {
            return false;
        }

        return "true".equals(MyApplication.aCache.getAsString(Contents.CACHE_KEY_AD_STATUS));
    }

    /**
     * 判断是否打开内容广告
     * 默认未打开
     *
     * @return 内容广告是否打开
     */
    public static boolean isOpenAdContent() {
        if (aCache == null) {
            return false;
        }

        String contentStatus = MyApplication.aCache.getAsString(Contents.CACHE_KEY_AD_CONTENT_STATUS);

        return "true".equals(contentStatus);
    }

    /**
     * 判断是否打开搜索框
     * 默认未打开
     *
     * @return 搜索框是否打开
     */
    public static boolean isOpenSearch() {
        if (aCache == null) {
            return false;
        }

        String searchStatus = MyApplication.aCache.getAsString(Contents.CACHE_KEY_SEARCH_SHOW);

        return "true".equals(searchStatus);
    }

    /**
     * 判断是否打开影视
     * 默认未打开
     *
     * @return 影视是否打开
     */
    public static boolean isOpenMovie() {
        if (aCache == null) {
            return false;
        }

        String searchStatus = MyApplication.aCache.getAsString(Contents.CACHE_KEY_MOVIE_SHOW);

        return "true".equals(searchStatus);
    }

    public static void agreeIsTrue() {
        MyApplication.aCache.put(Contents.CACHE_KEY_AGREE_AGREEMENT, "1");
        if (sp != null) {
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean(Contents.CACHE_KEY_AGREE_AGREEMENT, true);
            editor.apply();
        }
    }

    public static boolean isAgree() {
        boolean isAgree = "1".equals(MyApplication.aCache.getAsString(Contents.CACHE_KEY_AGREE_AGREEMENT));
        boolean isSpAgree;
        if (sp != null) {
            isSpAgree = sp.getBoolean(Contents.CACHE_KEY_AGREE_AGREEMENT, false);
        } else {
            isSpAgree = false;
        }
        return isAgree || isSpAgree;
    }

}
